package net.vkits.anjiamiao.application;

import net.vkits.anjiamiao.domain.model.Order;
import net.vkits.anjiamiao.domain.model.PayRecord;
import net.vkits.anjiamiao.domain.repository.OrderRepository;
import net.vkits.anjiamiao.domain.repository.PayRecordRepository;
import net.vkits.common.alipay.AlipayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;

/**
 * Created by ethan-liu on 2016/12/15.
 */
@Service
public class PayRecordApplicationService {

    private static final Logger logger = LoggerFactory.getLogger(PayRecordApplicationService.class);
    @Resource
    private PayRecordRepository payRecordRepository;
    @Resource
    private OrderRepository orderRepository;

    @Transactional
    public void addPayRecord(PayRecord record) {
        payRecordRepository.save(record);
        if (!record.getAppId().equals(AlipayConfig.APP_ID)) {
            logger.info("Unknown app id: {}", record.getAppId());
        }
        if (record.getSellerId().equals(AlipayConfig.seller_id)) {
            logger.info("Unknown seller id: {}", record.getSellerId());
        }
        if (record.getTradeStatus().equals("TRADE_SUCCESS")) {
            Order order = orderRepository.findByIdAndDeletedFalse(record.getOutTradeNo());
            if (order.getOriginalOrder().isAmountEquals(record.getTotalAmount())){
                order.finishedOrder();
            }
            orderRepository.save(order);
        }
    }

    public Page<PayRecord> getPayRecord(Pageable pageable) {
        return payRecordRepository.findAll(pageable);
    }
}
